<template>
	<view>
		当前沟通对象：{{userName}}
		<view class="message-list">
			<view class="message-item" v-for="(item, index) in messageList" :key="index">
					<view class="right" v-if="item.from === curUserId">
						<template v-if="typeof item.message ==='string'">
							<rich-text :nodes="item.message"></rich-text>
						</template>
						<template v-else>
							<view v-if="item.message.type==='audio'" @click="changePlay(item.message.url)">播放录音</view>
						</template>
						<up-avatar src="https://uview-plus.jiangruyi.com/h5/static/uview/album/6.jpg"></up-avatar>
					</view>
					<view class="left" v-else>
						<up-avatar src="https://uview-plus.jiangruyi.com/h5/static/uview/album/5.jpg"></up-avatar>
						<rich-text :nodes="item.message"></rich-text>
					</view>
				
			</view>
		</view>
		<button @touchstart="startRecord" @touchend="stopRecord">录音</button>
		<view class="send-model">
			<up-icon name="photo" @click="open"></up-icon>
			<up-icon name="play-left-fill" @mousedown="startRecord" @mouseup="stopRecord"></up-icon>
			<view class="input-content">
				<up-input class="input-model" placeholder="请输入内容" border="surround" v-model="message"></up-input>
				<!-- <view id='my-info' v-model="message" contenteditable class="message-shou" @input="changeContent">{{message}}</view> -->
			</view>
			<view class="right-icon">
				<text class="send-btn" @click="doSend">发送</text>
				<up-icon name="plus-circle"></up-icon>
				<up-icon name="camera" @click="selectImg"></up-icon>
			</view>
		</view>
		<up-popup :show="show" @close="close" mode="bottom">
			<view>
				<image class="icon-img" v-for="(item,index) in logoToFlag" :key="item.url" :src="item.url"
					@click="selectIcon(item.url)"></image>
			</view>
		</up-popup>
		<up-toast ref="uToastRef"></up-toast>
	</view>
</template>

<script setup>
	import {
		computed,
		ref
	} from 'vue';
	import io from '@hyoga/uni-socket.io';
	import {
		onLoad,
		onUnload
	} from '@dcloudio/uni-app'
	const logoToFlag = ref([{
			url: '/static/logo.png'
		},
		{
			url: '/static/publish.png'
		},
	])
	const show = ref(false)
	const uToastRef = ref(null)
	const message = ref('')
	const socket = ref('')
	const messageList = ref([])
	const curUserId = ref('')
	const toUserId = ref('')
	const userName = ref('')
	let timer = null
	const recorderManager = uni.getRecorderManager()
	const innerAudioContext = uni.createInnerAudioContext()
	// recorderManager.onStop = (res) => {
	// 	console.log(res)
	// }
	// const changeContent = (e) => {
	// 	console.log(e.target.innerText)
	// 	const dom = uni.createSelectorQuery().select('$my-info')
	// 	console.log(dom)
	// }
	// const changeMessage = () => {

	// }
	//开始不放录音事件
	const changePlay = (url) => {
		console.log(url,innerAudioContext.paused)
		innerAudioContext.src = url
		if(innerAudioContext.paused) {
			innerAudioContext.play()
		} else {
			innerAudioContext.pause()
		}
		
	}
	//点击表情图片的事件
	const startRecord  =() => {
		console.log('开始录音')
		// 点击开始录音
		recorderManager.start()
	}
	const stopRecord = () => {
		console.log('停止录音')
		recorderManager.stop()
	}
	
	const selectIcon = (flag) => {
		message.value += flag
		close()
	}
	// 定义方法  
	function open() {
		// 打开逻辑，比如设置 show 为 true  
		show.value = true;
		// console.log('open');  
	}

	function close() {
		// 关闭逻辑，设置 show 为 false  
		show.value = false;
		// console.log('close');  
	}
	const selectImg = () => {
		uni.chooseImage({
			success(res) {
				console.log(res)
				//获取到临时路径，res.tempFilePaths
				// 要去上传图片
				// 上传成功获取到服务器的文件地址
				setTimeout(() => {
					const url = 'https://ms.bdimg.com/pacific/0/pic/-265485872_687058773.png?x=0&y=0&h=150&w=242&vh=150.00&vw=242.00&oh=150.00&ow=242.00'
					message.value += `<img with="50" class="message-img" src="${res.tempFilePaths[0]}" />`
				}, 2000)
			}
		})
	}
	// 调用接口获取历史消息，赋值给messageList
	const doConnect = () => {
		socket.value = io('http://localhost:3001', {
			path: '/socket',
			query: {
				userId: curUserId.value
			},
			transports: ['websocket', 'polling'],
			timeout: 5000,
		});
		socket.value.on('connect', () => {
			console.log('加入聊天室成功')
			timer = setInterval(() => {
				socket.value.emit('send', {
					type: 'heart'
				})
			}, 60000)
			socket.value.on('reciveMessage', (obj) => {
				console.log('接受到服务器端的消息了', obj)
				if (obj !== 'pang') {
					if (typeof obj.message === 'string') {
						//就是把标识转换成{type:image,url:'***'}
						if(typeof obj.message === 'string') {
							obj.message = getMessageStr(obj.message)
						}
						messageList.value.push(obj)
					} else if (obj.message) {
						messageList.value.push(obj)
					}

				}

			})
		})
	}
	const getMessageStr = (str) => {
		let result = str
		// [{url:'/a.png'}, {url:'/b.png'}]
		// 原字符串：/a.png/b.png
		// <img src="<img src="/a.png">" />/b.png
		logoToFlag.value.map(item => {
			// 判断
			if (str.indexOf(item.url) >= 0 && str.indexOf(`src="${item.url}"`) === -1) {
				result = result.replaceAll(item.url,
					`<img with="50" src="${item.url}" class="message-img" />`)
			}
		})
		return result
	}
	// 发消息：1. 私发：给某人单独发 2.群发：我要给聊天室里的每一个人都要发消息
	onLoad((options) => {
		console.log(options.userId, options.userName)
		toUserId.value = options.userId
		userName.value = options.userName
		curUserId.value = options.id || 'bin'
		recorderManager?.onStop(function (res) {
			console.log('recorder stop' + JSON.stringify(res));
			// self.voicePath = res.tempFilePath;
			// 拿到录音文件的临时路径，进行上传，上传成功获取到服务器返回的录音文件地址
			setTimeout(() => {
				console.log('录音上传成功')
				const url = 'https://web-ext-storage.dcloud.net.cn/uni-app/ForElise.mp3'	
				message.value = {type: 'audio', url}
			})
		});
		doConnect()
	})
	const doSend = () => {
		const token = uni.getStorageSync('token')
		if (!token) {
			//肯定没有登录
			uToastRef.value.show({
				type: 'error',
				icon: false,
				message: "请去登陆",
				iconUrl: 'https://cdn.uviewui.com/uview/demo/toast/error.png'
			})
			return
		}
		const messageItem = {
			from: curUserId.value,
			message:typeof message.value === 'string' ? getMessageStr(message.value) : message.value,
			to: toUserId.value
		}
		// socket.value.send('messageItem')
		socket.value.emit('send', messageItem)
		messageList.value.push(messageItem)
		message.value = ''
		console.log(message.value)
	}
	onUnload(() => {
		console.log('22222')
		socket.value.disconnect()
	})
	// const changeMessigeInfo = () => {

	// } 
	// const messageInfo = computed(() => {
	// 	logoToFlag.forEach(item => {
	// 		const index = message.value.indexOf(item.url)
	// 		if(index>=0) {

	// 		}

	// 	})
	// })
	// const doConnect = () => {
	// 	socket.on('connect', () => {
	// 		console.log('连接成功')
	// 	})
	// }
	// doConnect()
</script>

<style lang="scss" scoped>
	.icon-img {
		width: 50rpx;
		height: 50rpx;
	}
	.message-img{
		width: 50rpx;
	}
	.send-model {
		position: fixed;
		bottom: 0;
		width: 100%;
		box-sizing: border-box;
		height: 150rpx;
		display: flex;
		align-items: center;
		padding: 0 20rpx;

		.input-content {
			margin: 0, 20rpx;
			flex: 1;
		}

		.message-shou {
			width: 100%;
			border: 1px solid #000;
		}

		// .input-model {
		// 	width: ;
		// 	margin: 0 20rpx;
		// 	display: none;
		// }

		.right-icon {
			display: flex;
			align-items: center;
			flex-wrap: nowrap;
		}
	}

	.send-btn {
		background: #2491F8;
		padding: 10rpx;
	}

	.left {
		display: flex;
		justify-content: flex-start;
	}

	.right {
		display: flex;
		justify-content: flex-end;
	}
</style>